import { UserOutlined, KeyOutlined } from "@ant-design/icons";
import { Button, Space,Input} from "antd";
import { useState,useEffect } from "react";
import { getRegister } from "../tools/ajax";
import { useNavigate } from "react-router-dom";
import "./user.css";


export default function User(props) {

  let [username, setUsername] = useState("");
  let [password1, setPassword1] = useState("");
  let [password2, setPassword2] = useState("");
  let [usererr, setUsererr] = useState("");
  let [pwderr1, setPwderr1] = useState("");
  let [pwderr2, setPwderr2] = useState("");
  const navigate = useNavigate();

  async function register() {
    var nameReg = /^[\w\u4e00-\u9fa5]{2,8}$/;
    if (!nameReg.test(username)) {
      setUsererr("只能包含数字、字母、下划线、汉字2-8位");
      return false;
    }

    // 密码正则验证
    var pwdReg = /^\w{6,12}$/;
    if (!pwdReg.test(password1)) {
      setPwderr1("只能包含数字、字母、下划线6-12位");
      return false;
    }

    // 确认密码
    if (password1 != password2) {
      setPwderr2("两次输入的密码不一致") 
      return false;
    }

    var { data: res } = await getRegister({
      userName: username,
      password: password1,
    });

    if (res.code == 0) {
      alert('用户名被占用')
      username = usererr = password1 = pwderr1 = "";
    } else {
      alert('注册成功，赶快去登录吧')
      setTimeout(()=>{
        navigate("/login")
      },1000)
    } 
  }

  return (
    <div className="logins">
      <Input
        size="large"
        placeholder="用户名"
        prefix={<UserOutlined />}
        style={{
          width: 400,
          height:40
        }}
        value={username}
        onChange={(e) => {
          setUsername(e.target.value);
        }}
        onFocus={() => {
          usererr = "";
        }}
      />
      <br />
      <br />
      <Input.Password
        size="large"
        placeholder="密码"
        prefix={<KeyOutlined />}
        value={password1}
        onChange={(e) => {
          setPassword1(e.target.value);
        }}
        onFocus={() => {
          pwderr1 = "";
        }}
        style={{
          width: 400,
          height:40
        }}
      />
      <br />
      <br />
      <Input.Password
        size="large"
        placeholder="确认密码"
        prefix={<KeyOutlined />}
        value={password2}
        onChange={(e) => {
          setPassword2(e.target.value);
        }}
        onFocus={() => {
          pwderr2 = "";
        }}
        style={{
          width: 400,
          height:40
        }}
      />
      <br />
      <br />
      <Space wrap>
        <Button
          type="primary"
          style={{
            width: 400,
            height:40,
          }}
          onClick={register}
        >
          注册
        </Button>
      </Space>
    </div>
  );
}
